/**
 * VConsole 全局初始化脚本
 * 为所有页面添加调试控制台功能，并支持跨页面保存日志
 */
(function() {
    // 日志存储与恢复功能
    const vConsoleStorage = {
        // 最大存储日志数量
        maxLogs: 1000,
        
        // 存储日志到localStorage
        saveLogs: function(logs) {
            try {
                // 只保存最新的maxLogs条日志
                if (logs.length > this.maxLogs) {
                    logs = logs.slice(logs.length - this.maxLogs);
                }
                localStorage.setItem('vConsole_logs', JSON.stringify(logs));
            } catch (e) {
                console.error('保存VConsole日志失败:', e);
            }
        },
        
        // 从localStorage获取日志
        getLogs: function() {
            try {
                const logsJson = localStorage.getItem('vConsole_logs');
                return logsJson ? JSON.parse(logsJson) : [];
            } catch (e) {
                console.error('获取VConsole日志失败:', e);
                return [];
            }
        },
        
        // 清空日志
        clearLogs: function() {
            try {
                localStorage.removeItem('vConsole_logs');
            } catch (e) {
                console.error('清空VConsole日志失败:', e);
            }
        }
    };
    
    // 检查是否启用vConsole (从AppConfig或common.js中获取设置)
    var shouldEnableVConsole = false;
    
    // 如果AppConfig存在并且设置了enableVConsole
    if (window.AppConfig && typeof window.AppConfig.enableVConsole !== 'undefined') {
        shouldEnableVConsole = window.AppConfig.enableVConsole;
    }
    
    // 如果未启用vConsole，则直接返回
    if (!shouldEnableVConsole) {
        return;
    }
    
    // 创建全局变量以跟踪初始化状态
    window._vConsoleInitialized = window._vConsoleInitialized || false;
    
    // 如果已经初始化，则直接返回
    if (window._vConsoleInitialized || window.vConsole) {
        console.log('VConsole 已经初始化，跳过重复初始化');
        return;
    }
    
    // 如果VConsole未定义，先加载库文件
    if (typeof VConsole === 'undefined') {
        console.log('VConsole未加载，正在加载库文件...');
        
        // 确定当前页面相对路径
        var basePath = '';
        // 检查是否在子目录中
        if (window.location.pathname.includes('/page/')) {
            basePath = '../';
        }
        
        var script = document.createElement('script');
        script.src = basePath + 'lib/vconsole/vconsole.min.js';
        
        script.onload = function() {
            console.log('VConsole库加载成功，开始初始化...');
            initVConsole();
        };
        
        script.onerror = function() {
            console.error('VConsole库加载失败，请检查路径是否正确');
        };
        
        document.head.appendChild(script);
    } else {
        // VConsole已加载，直接初始化
        initVConsole();
    }
    
    function initVConsole() {
        try {
            // 创建VConsole实例
            window.vConsole = new VConsole({
                defaultPlugins: ['system', 'network', 'element', 'storage'],
                maxLogNumber: 1000,
                theme: 'dark',
                // 初始化完成后的回调
                onReady: function() {
                    // 恢复之前保存的日志
                    const savedLogs = vConsoleStorage.getLogs();
                    if (savedLogs && savedLogs.length > 0) {
                        // 将保存的日志添加到控制台
                        console.info('=====================================');
                        console.info(`从上一页面恢复了 ${savedLogs.length} 条日志`);
                        console.info('=====================================');
                        
                        // 遍历添加日志
                        savedLogs.forEach(log => {
                            switch (log.type) {
                                case 'log': console.log(log.content); break;
                                case 'info': console.info(log.content); break;
                                case 'warn': console.warn(log.content); break;
                                case 'error': console.error(log.content); break;
                                default: console.log(log.content);
                            }
                        });
                    }
                }
            });
            
            // 标记为已初始化
            window._vConsoleInitialized = true;
            
            // 确保VConsole按钮可见
            setTimeout(function() {
                var vconsoleBtn = document.querySelector('.vc-switch');
                if (vconsoleBtn) {
                    vconsoleBtn.style.display = 'block';
                    vconsoleBtn.style.position = 'fixed';
                    vconsoleBtn.style.bottom = '10px';
                    vconsoleBtn.style.right = '10px';
                    vconsoleBtn.style.zIndex = '10000';
                    console.log('VConsole按钮样式已设置');
                } else {
                    console.error('未找到VConsole按钮元素');
                }
            }, 500);
            
            // 打印初始化成功信息
            console.info('=====================================');
            console.info('VConsole 初始化成功 - vconsole-init.js');
            console.info('当前页面: ' + window.location.href);
            console.info('App版本: ' + (window.AppConfig ? window.AppConfig.version : '未知'));
            console.info('设备信息: ' + navigator.userAgent);
            console.info('=====================================');
            
            // --- PERFORMANCE OPTIMIZATION ---
            // Debounce function to limit the frequency of localStorage writes.
            const debounce = (func, wait) => {
                let timeout;
                return function executedFunction(...args) {
                    const later = () => {
                        clearTimeout(timeout);
                        func(...args);
                    };
                    clearTimeout(timeout);
                    timeout = setTimeout(later, wait);
                };
            };
            
            // Heavy-duty operations that we want to debounce.
            const saveLogsToStorage = () => {
                vConsoleStorage.saveLogs(currentLogs);
            };

            // Create a debounced version of the save function.
            // This will ensure we only write to localStorage at most once every 2 seconds.
            const debouncedSaveLogs = debounce(saveLogsToStorage, 2000);
            // --- END OPTIMIZATION ---

            // 重写console方法以保存日志
            const originalConsole = {
                log: console.log,
                info: console.info,
                warn: console.warn,
                error: console.error
            };
            
            // 当前内存中的日志
            let currentLogs = vConsoleStorage.getLogs();
            
            // 重写console方法
            console.log = function() {
                // 调用原始方法
                originalConsole.log.apply(console, arguments);
                // 保存日志
                const content = Array.from(arguments).map(arg => {
                    if (typeof arg === 'object') {
                        try {
                            return JSON.stringify(arg);
                        } catch (e) {
                            return String(arg);
                        }
                    }
                    return String(arg);
                }).join(' ');
                currentLogs.push({type: 'log', content: content, time: new Date().getTime()});
                debouncedSaveLogs(); // Use debounced save
            };
            
            console.info = function() {
                originalConsole.info.apply(console, arguments);
                const content = Array.from(arguments).map(arg => String(arg)).join(' ');
                currentLogs.push({type: 'info', content: content, time: new Date().getTime()});
                debouncedSaveLogs(); // Use debounced save
            };
            
            console.warn = function() {
                originalConsole.warn.apply(console, arguments);
                const content = Array.from(arguments).map(arg => String(arg)).join(' ');
                currentLogs.push({type: 'warn', content: content, time: new Date().getTime()});
                debouncedSaveLogs(); // Use debounced save
            };
            
            console.error = function() {
                originalConsole.error.apply(console, arguments);
                const content = Array.from(arguments).map(arg => String(arg)).join(' ');
                currentLogs.push({type: 'error', content: content, time: new Date().getTime()});
                debouncedSaveLogs(); // Use debounced save
            };
            
            // 添加清除日志的方法
            window.clearVConsoleLogs = function() {
                currentLogs = [];
                vConsoleStorage.clearLogs();
                console.info('已清空所有VConsole日志');
            };
            
            // 监听JavaScript错误
            window.addEventListener('error', function(event) {
                console.error('JavaScript错误:', event.message, 'at', event.filename, 'line', event.lineno);
            });
            
            // 页面卸载时保存日志
            window.addEventListener('beforeunload', function() {
                // Ensure any pending logs are saved before leaving.
                vConsoleStorage.saveLogs(currentLogs);
            });
        } catch (e) {
            console.error('VConsole初始化失败:', e);
        }
    }
})(); 